package cn.sh.library.mgts.utils;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collector;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.bulk.BulkAction;
import org.elasticsearch.action.bulk.BulkProcessor;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.geo.builders.ShapeBuilder;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.databind.deser.Deserializers.Base;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import cn.sh.library.mgts.common.Constant;

public class JestUtil {

	private static int getPageCount(JsonObject jsonObject) {
		try {
//			System.out.println(getJsonElementByPath(Constant.PATH_TO_COUNT, jsonObject));;
		} catch (Exception e) {
			// TODO: handle exception
		}
		return 0;
	}

	public static String getJsonStringByPath(String path, JsonObject jsonObject) {
		try {
			JsonElement element = getJsonElementByPath(path, jsonObject);
			if (element == null) {
				return "";
			}
			return element.getAsString();
		} catch (Exception e) {
			return "";
		}
	}

	public static JsonElement getJsonElementByPath(String path, JsonObject jsonObject) {
		if (jsonObject != null) {
			String[] keys = getKeys(path);
			if (keys != null) { // keys would never be null in a standard search scenario (i.e.: unless search
								// class is overwritten)
//                String sourceKey = keys[keys.length - 1];
				JsonElement obj = jsonObject.get(keys[0]);
				if (obj == null) {
					return null;
				}
				for (int i = 1; i < keys.length; i++) {
					obj = ((JsonObject) obj).get(keys[i]);
				}
				return obj;
			}
		}

		return null;
	}

	public static String getJsonStringByPath4TemporalValue(String path, JsonObject jsonObject) {
		try {
			JsonElement element = getJsonElementByPath4TemporalValue(path, jsonObject);
			if (element == null) {
				return "";
			}
			return element.getAsString();
		} catch (Exception e) {
			return "";
		}
	}

	public static JsonElement getJsonElementByPath4TemporalValue(String path, JsonObject jsonObject) {
		if (jsonObject != null) {
			String[] keys = getKeys(path);
			if (keys != null) {
				JsonElement obj = jsonObject.get(keys[0]);
				if (obj == null) {
					return null;
				}
				// 判断是否为数组多值 --- 如：[{"@value":"清光緒三十三年（1907）"},{"@value":"1907"}]
				if (obj.isJsonArray()) {
					JsonArray array = obj.getAsJsonArray();
					for (int i = 0; i < array.size(); i++) {
						JsonElement element = array.get(i).getAsJsonObject().get("@value");
						String elementValue = element.toString().replace("\"", "");
						// 判断是否为数字, 取非数字字段
						if (StringUtilC.getInteger(elementValue) == null) {
							return element;
						}
					}
					// END BY CM
				} else {
					for (int i = 1; i < keys.length; i++) {
						obj = ((JsonObject) obj).get(keys[i]);
					}
					return obj;
				}
			}
		}
		return null;
	}

	// getJsonString--数组 单值
	public static String getAllJsonStringByPath(String path, JsonObject jsonObject, int size) {
		try {
			String obj = getAllJsonElementByPath(path, jsonObject, size);
			if (obj == null) {
				return "";
			}
			return obj;
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}

	public static String getAllJsonElementByPath(String path, JsonObject jsonObject, int size) {
		if (jsonObject != null) {
			String[] keys = getKeys(path);// [item,shelfMark](shelfMark拼接) /[provisionActivity,proDate]/[provision] /
											// [provisionActivity,proPlace,@value]
			if (keys != null) {
				JsonElement obj = jsonObject.get(keys[0]);// [{xx},{xx},{xx}]/{xx}
				if (obj == null) {
					return null;
				}
				// 数组形式（拼接/取单值（多层、单层））
				// 非数组形式（多层、单层）
				if (obj.isJsonArray()) {
					JsonArray array = obj.getAsJsonArray();
//					if (keys[0].equals("item") || keys[0].equals("notes")) {
//						String returnStr = "";
//						// 取值拼接
//						for (int i = 0; i < array.size(); i++) {
//							JsonElement element = array.get(i).getAsJsonObject().get(keys[1]);// item层级-item-shelfMark/其他多层之后改
//							returnStr += element.getAsString() + ";";
//						}
//						return returnStr;
//					} else {
					switch (keys.length) {
					case 1:
						String str = "";
						for(int i = 0;i<array.size();i++) {
							str += array.get(i).toString().replace("\"", "")+";";
						}
						return str;
					case 2:
						obj = array.get(size).getAsJsonObject().get(keys[1]);
						break;
					case 3:
						if (array.get(size).getAsJsonObject().get(keys[1]) != null) {
							if (array.get(size).getAsJsonObject().get(keys[1]).isJsonArray()) {
								obj = array.get(size).getAsJsonObject().get(keys[1]).getAsJsonArray().get(0)
										.getAsJsonObject().get(keys[2]);
							} else {
								obj = array.get(size).getAsJsonObject().get(keys[1]).getAsJsonObject().get(keys[2]);
							}
						} else {
							return null;
						}
						break;
					default:
						break;
					}
					if (obj == null) {
						return null;
					}
					return obj.getAsString();
//					}
				} else {
					try {
						JsonElement arrayObj = obj.getAsJsonObject().get(keys[1]);
						if (arrayObj == null) {
							return null;
						}
						if (arrayObj.isJsonArray()) {
							JsonArray array = arrayObj.getAsJsonArray();
							for (int j = 0; j < array.size(); j++) {
								if ("\"zh-cn\"".equals(array.get(j).getAsJsonObject().get("@language").toString())) {
									obj = array.get(j).getAsJsonObject().get(keys[2]);
									continue;
								}
							}
						} else {
							for (int i = 1; i < keys.length; i++) {
								obj = ((JsonObject) obj).get(keys[i]);
							}
						}
					} catch (Exception e) {
						for (int i = 1; i < keys.length; i++) {
							obj = ((JsonObject) obj).get(keys[i]);
						}
					}
					try {
						return obj==null ? null : obj.getAsString().replace("\"", "");	
					} catch (Exception e) {
						e.printStackTrace();
						System.out.println(path + jsonObject);
						return null;
					}
				}
			}
		}
		return null;
	}

	public static String getJsonStringByPath4ItemDescription(String path, JsonObject jsonObject) {
		try {
			JsonElement element = getJsonElementByPath4ItemDescription(path, jsonObject);
			if (element == null) {
				return "";
			}
			return element.getAsString();
		} catch (Exception e) {
			return "";
		}
	}

	public static JsonElement getJsonElementByPath4ItemDescription(String path, JsonObject jsonObject) {
		Gson gson = new Gson();
		String description = "";
		if (jsonObject != null) {
			String[] keys = getKeys(path);
			if (keys != null) {
				JsonElement obj = jsonObject.get(keys[0]);
				if (obj == null) {
					return null;
				}
				// 判断是否为数组多值 --- 如：[{"@value":"STJP000176"},{"@value":"清光緒元年（1875）木活字本，一册。"}]
				if (obj.isJsonArray()) {
					JsonArray array = obj.getAsJsonArray();
					for (int i = 0; i < array.size(); i++) {
						JsonElement element = array.get(i).getAsJsonObject().get("@value");
						description += element.getAsString() + ";";
					}
					// 去除末尾的";"号
					String result = description.substring(0, description.length() - 1);
					return gson.toJsonTree(result);

					// END BY CM
				} else {
					for (int i = 1; i < keys.length; i++) {
						obj = ((JsonObject) obj).get(keys[i]);
					}
					return obj;
				}
			}
		}
		return null;
	}

	public static JsonArray getHits(JsonObject jsonObject) {
		JsonElement jsonElement = getJsonElementByPath(Constant.PATH_TO_HITS, jsonObject);

		if (jsonElement.isJsonObject()) {
			JsonArray jsonArray = new JsonArray();
			jsonArray.add(jsonElement);
			return jsonArray;
		} else if (jsonElement.isJsonArray()) {
			return jsonElement.getAsJsonArray();
		}
		return null;
	}

	private static String[] getKeys(String pathToResult) {
		return pathToResult == null ? null : pathToResult.split("[.]");
	}
}
